<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsF8OKGkWhR7IcTZjJZg/rEPiq7Ehc/4jhtoyKx62YvBZr/OJ4of6Mrn/1RSOayYRj7WIAnDg87TRbTxj7xWtRXFoHpSRemUobtYFPFIUug2BImaPDvDae+/ZXJhzcmdV2ChUA/1DOchYcry/MblFZIYDVxXU+tZL+Din8c9bGPWI4uoKB7rXd3c5oSHFmAX5K4l33xGF/PtUWpK/DpzABE46DQt7ZcuRYN53C/CRWRG+7NG73vFqjgwsSnaZjQXw/c4cSSAZ4oUkVMi9nU4nIkhp140R2aW86uRKNgHUNt4sFy6NOOegRV6m5sjqtZpkAZtCkN9inwlXtda0Dm6UjwIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1xh8a1HUp8IYM9Bu0OXDGo6/2dRYgIic5MDU5qvDTbyiM+p8gl8dVgp2PqMeADExJK6UwayEXFypnr1hQcd613Npg+VKyiaLqVmY0WUDxjlRMj2qEXgx0ZBzKdM33g1218yG5QA/b9LO3/K+FByrFFLtL4gpAdhpcRcKYTYCMaUC5nKug0uguschFD7dY2pnOeL11t6wIup37/NCuwx+h3sjhPnWXr/Q/TltGMBUhFaSfnCxl3ejK803UuloQhiJRoCeBguYqfHT+EZLOTtDXa6DmpZwp3IjP8Fg70isVYXV2QIeqDKsLQpi3huVQA0ordotddUsiFBEMzslQ41BXQIDAQAB",
        'private_key' => 'MIIEpAIBAAKCAQEA1xh8a1HUp8IYM9Bu0O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YSr1uxqrKWO2CciMz4CpuOTUopQLltv5zcOgD+WceQXNxLqAZef9YAX7hovj5bEHZ4H+uH3aFTND4FMetApkYFCEQUNOL+6uBirwY0EvGq/QWXr5ECgYEAhZiqC6y1T6NBt7X+R+dm51VutmZx4TC0GQp3gLd85+YD+LVlkjNyHf3XzCAaCbLyGlU4al9D5moXxbGKFTFkOhDiE8/QRtjuCHy/WMTcbnNuHq/TbAB3p2S3u7EFsHmKEX6ZhsRl/PVN1yARyZDqEmMaEjzGHgZWBAQqXuMtNeECgYAcXL6LPsIQp/B3UagHqpyi0iR/RO5QMIt1wJy1Z5Ltyz2AfKBa3Y9J0xETJMwFq2RJ7CsLwazm9BIZDIVpiGp6lkNdtu9YYy108y3VkIo/EHZDQqpC0DwgB+0NxAyYWy9U2Zl383twdLssoWZxtqh0HKeH9MvqqlDeuiq5+L+4gA=='
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//喵额
    public $out_trade_no;//订单号
    
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//    public function getParam(){
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
//        $money = '0.01';
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2019033063737847";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://heart.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return string|void
     * user_id：用户ID,
     * type：1 课程购买  2 捐赠  3 打赏
     * price：打赏或捐赠的价格，当type为2或者3时传
     * activity_id：捐赠的活动ID，当type为2时，传此值
     */
    public function alipay()
    {
        extract(input());
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }

        if($params['type']==1){//研学活动支付
            $result = Db::table('up_notice_order')->alias('a')
                ->join('up_notice un','un.n_id = a.n_id')
                ->where('notice_id',$params['id'])->field('a.*,un.n_money')->find();
            $this->body = '橡榛教育';
            $this->subject = '橡榛教育';
            $this->total_amount =$result['n_money'];
            $this->out_trade_no = $result['notice_num'];
        }else{
            //查询这个订单详情
            $info = Db::table('up_order')->where('order_id',$params['id'])->find();
            if($info['order_id']==''){
                return json_encode(['status' => 0, 'msg' => '订单不存在']);
            }

            //查询订单里面每个商品的详情
            $goodInfo  = Db::table('up_order_info')->where('oi_order_id',$params['id'])->select();
            //判断库存数量
            foreach ($goodInfo as $key=>$vo){
                $result = Db::table('up_goods')->where('good_id',$vo['oi_good_id'])->find();
                if($vo['oi_type']==2){//图书
                    if($vo['oi_num']>$result['good_stock']){
                        return json_encode(['status' => 0, 'msg' => '抱歉,您选购的'.$result['good_name'].'数量大于剩余库存数量,请重新选择']);
                    }
                }elseif ($vo['oi_type']==1){//非图书
                    $result1 = Db::table('up_good_spec')->where('spec_id',$vo['oi_spec_id'])->find();
                    if($vo['oi_num']>$result1['spec_stock']){
                        return json_encode(['status' => 0, 'msg' => '抱歉,您选购的'.$result['good_name'].'商品暂时无货']);
                    }
                }
            }
            if($info['order_hh_payment']==3){//人民币支付
//            $order = array();
//            $order['body'] = $this->body;//描述
//            $order['total_fee'] = $this->total_fee;//订单喵额
//            $order['out_trade_no'] = $this->out_trade_no;//订单号
//            $order['product_id'] = '';//产品ID
//            $order['trade_type'] = 'APP';//类型
//            $respont = $this->WeChatPayReady($order);
//            return json_encode(['status'=>200,'msgsss'=>$respont]);
                $this->body = '橡榛教育';
                $this->subject = '橡榛教育';
                $this->total_amount =$info['order_user_pay'];
                $this->out_trade_no = $info['order_number'];
            }elseif ($info['order_hh_payment']==2){//喵币支付
                //查询喵币兑换的次数
                $num = Db::table('up_convert')->where('convert_id',1)->find();
                $start = date('Y-m-d H:i:s',strtotime('-24 hours'));
                $end = date('Y-m-d H:i:s',time());
                //查询当前时间24小时之前购物的商品记录
                $where['order_time'] = array('between',array($start,$end));
                $where['order_userid'] = $user_id;
                $where['order_hh_payment'] = array('IN','1,2');
                $where['order_status'] = array('IN','2,3,4');
                $count = Db::table('up_order')->where($where)->count();
                if($count>=$num['convert_num']){
                    return json_encode(['status'=>0,'msg'=>"规定时间内兑换喵币次数超过默认限制"]);
                }
                //查询这个用户的喵币
                $user_integral = Db::table('up_u_user')->where('user_id',$user_id)->value('user_integral');
                if($info['order_j_glod']>$user_integral){//证明购买花费的喵币大于用户账号的喵币数量
                    return json_encode(['status'=>100,'msg'=>"喵币不足不能购买"]);
                }else{
                    $this->body = '橡榛教育';
                    $this->subject = '橡榛教育';
                    $this->total_amount =$info['order_user_pay'];
                    $this->out_trade_no = $info['order_number'];
                }
            }elseif ($info['order_hh_payment']==1){//混合支付

                $num = Db::table('up_convert')->where('convert_id',1)->find();
                $start = date('Y-m-d H:i:s',strtotime('-24 hours'));
                $end = date('Y-m-d H:i:s',time());
                //查询当前时间24小时之前购物的商品记录
                $where['order_time'] = array('between',array($start,$end));
                $where['order_userid'] = $user_id;
                $where['order_hh_payment'] = array('IN','1,2');
                $where['order_status'] = array('IN','2,3,4');
                $count = Db::table('up_order')->where($where)->count();
                if($count>=$num['convert_num']){
                    return json_encode(['status'=>0,'msg'=>"规定时间内兑换喵币次数超过默认限制"]);
                }
                //查询这个用户的喵币
                $user_integral = Db::table('up_u_user')->where('user_id',$user_id)->value('user_integral');
                if($info['order_j_glod']>$user_integral){//证明购买花费的喵币大于用户账号的喵币数量
                    return json_encode(['status'=>100,'msg'=>"喵币不足不能购买"]);
                }
                $this->body = '橡榛教育';
                $this->subject = '橡榛教育';
                $this->total_amount =$info['order_user_pay'];
                $this->out_trade_no = $info['order_number'];
            }
        }
            $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
            return json_encode($respont);
    }
    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        //$this->write_admin_log($getInfo);
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans();
                try{
                    $num = $getInfo['out_trade_no'];//订单号
                    $dataOrder = array();
                    $dataAll = Db::table('up_notice_order')->where('notice_num',$num)->find();
                    if($dataAll['notice_id']!=''){
                        //研学活动
                        $haveC = Db::table('up_studies')->where('st_id', $dataAll['studies_id'])->find();
                        if($haveC['st_pay_status'] != 1){
                            die('success');
                        }
                        Db::table('up_notice')->where('n_id', $dataAll['n_id'])->setInc('n_num_already');
                        $res1 = Db::table('up_notice')->where('n_id', $dataAll['n_id'])->find();
                        $data2['st_pay_status'] = 2;
                        $data2['st_pay_time'] = date('Y-m-d H:i:s',time());
                        $data2['st_pay_num'] = $num;
                        $res2 = Db::table('up_studies')->where('st_id', $dataAll['studies_id'])->update($data2);
                        $data1['notice_status'] = 2;
                        $data1['notice_pay_time'] = date('Y-m-d H:i:s',time());
                        $res3 = Db::table('up_notice_order')->where('notice_id', $dataAll['notice_id'])->update($data1);
                        $resultAll1['revenue_name'] = $dataAll['notice_num'];
                        $resultAll1['revenue_time'] = date('Y-m-d H:i:s',time());
                        $resultAll1['revenue_type'] = 2;
                        $resultAll1['revenue_status'] = 1;
                        $resultAll1['revenue_price'] = $res1['n_money'];
                        $resultAll1['revenue_gl_id'] = $res1['n_id'];
                        Db::table('up_revenue')->insert($resultAll1);
                        Db::commit();
                        die('success');
                    }else{
                        //商城
                        $dataOrder['order_paytime'] = $getInfo['gmt_payment'];//支付时间
                        $dataOrder['order_status'] = 2;
                        $info = Db::table('up_order')->where('order_number',$num)->find();
                        if($info['order_id']!=''){
                            if($info['order_status'] != 1){
                                die('success');
                            }
                            $aa = Db::table('up_order')->where('order_number',$num)->update($dataOrder);
                            $All = Db::table('up_order_info')->where('oi_order_id',$info['order_id'])->select();
                            if($info['order_hh_payment']==1){//混合支付
                                //修改用户账户的余额
                                Db::table('up_u_user')->where('user_id',$info['order_userid'])->setDec('user_integral',$info['order_j_glod']);
                                $resultAll['glod_user_id'] =$info['order_userid'];
                                $resultAll['glod_status'] =5;
                                $resultAll['glod_type'] =1;
                                $resultAll['glod_money'] =$info['order_j_glod'];
                                $resultAll['glod_time'] =date('Y-m-d H:i:s',time());
                                Db::table('up_glod')->insertGetId($resultAll);

                                foreach ($All as $key=>$vo){//循环减库存
                                    if($vo['oi_type']==1){//人民币
                                        Db::table('up_good_spec')->where('spec_id',$vo['oi_spec_id'])->setDec('spec_stock',$vo['oi_num']);
                                        Db::table('up_goods')->where('good_id',$vo['oi_good_id'])->setDec('good_stock',$vo['oi_num']);
                                        //加销量
                                        Db::table('up_goods')->where('good_id',$vo['oi_good_id'])->setInc('good_sales_num',$vo['oi_num']);

                                    }elseif ($vo['oi_type']==2){//喵币
                                        Db::table('up_goods')->where('good_id',$vo['oi_good_id'])->setDec('good_stock',$vo['oi_num']);
                                        //加销量
                                        Db::table('up_goods')->where('good_id',$vo['oi_good_id'])->setInc('good_sales_num',$vo['oi_num']);

                                    }
                                }
                                $this->getHonorForEvery($info['order_userid'],10);

                            }elseif ($info['order_hh_payment']==3){
                                //人民币支付
                                foreach ($All as $key=>$vo){//循环减库存
                                    Db::table('up_good_spec')->where('spec_id',$vo['oi_spec_id'])->setDec('spec_stock',$vo['oi_num']);
                                    //加销量
                                    Db::table('up_goods')->where('good_id',$vo['oi_good_id'])->setInc('good_sales_num',$vo['oi_num']);
                                }
                                if($info['order_is_coupon']==1){
                                    $this->getHonorForEvery($info['order_userid'],10);
                                }
                            }elseif ($info['order_hh_payment']==2){//喵币支付
                                //修改用户账户的余额
                                Db::table('up_u_user')->where('user_id',$info['order_userid'])->setDec('user_integral',$info['order_j_glod']);
                                $resultAll['glod_user_id'] =$info['order_userid'];
                                $resultAll['glod_status'] =5;
                                $resultAll['glod_type'] =1;
                                $resultAll['glod_money'] =$info['order_j_glod'];
                                $resultAll['glod_time'] =date('Y-m-d H:i:s',time());
                                Db::table('up_glod')->insertGetId($resultAll);
                                foreach ($All as $key=>$vo){
                                    Db::table('up_goods')->where('good_id',$vo['oi_good_id'])->setDec('good_stock',$vo['oi_num']);
                                    //加销量
                                    Db::table('up_goods')->where('good_id',$vo['oi_good_id'])->setInc('good_sales_num',$vo['oi_num']);
                                }
                                $this->getHonorForEvery($info['order_userid'],10);

                            }
//                    if($info['order_is_coupon']==1){
//                        Db::table('up_my_coupon')->where('mc_id',$info['order_my_coupon'])->setField('mc_status',2);
//                    }
                            //插入营收表
                            $resultAll1['revenue_name'] = $num;
                            $resultAll1['revenue_time'] = date('Y-m-d H:i:s',time());
                            $resultAll1['revenue_type'] = 1;
                            $resultAll1['revenue_status'] = 1;
                            $resultAll1['revenue_price'] = $info['order_user_pay'];
                            $resultAll1['revenue_glod'] = $info['order_j_glod'];
                            $resultAll1['revenue_gl_id'] = $info['order_id'];
                            Db::table('up_revenue')->insert($resultAll1);
                        }
                        Db::commit();
                        die('success');
                    }
                }catch(\Exception $e){
                    Db::rollback();//回滚
                    return 'error';
                }
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019033063737847';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }
}